package com.apobates.forum.thrones.admin.controller;

import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.member.entity.ForumCalendarUnitEnum;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberPenalizeRecords;
import com.apobates.forum.member.entity.MemberStatusEnum;
import com.apobates.forum.member.service.MemberPenalizeRecordsService;
import com.apobates.forum.member.service.MemberService;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.admin.controller.form.MemberPenalizeForm;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;

/**
 * 会员惩罚记录控制器
 *
 * @author xiaofanku
 * @since 20190722
 */
@Controller
@RequestMapping(value = "/member/penalize")
public class AdminMemberPenalizeRecordsController {
    @Autowired
    private MemberPenalizeRecordsService memberPenalizeRecordsService;
    @Autowired
    private MemberService memberService;
    @Value("${site.pageSize}")
    private int pageSize;
    
    @GetMapping(path = "/")
    public String listPage(
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            HttpServletRequest request,
            Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/member/penalize/").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<MemberPenalizeRecords> rs = memberPenalizeRecordsService.getAll(pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/member_penalize/index";
    }
    
    //创建
    @GetMapping(path = "/create")
    public String createForm(
            @RequestParam(name = "member", required = false, defaultValue = "0") long memberId,
            @RequestParam(name = "names", required = false, defaultValue = "") String names,
            HttpServletRequest request,
            Model model) {
        MemberPenalizeForm form = new MemberPenalizeForm();
        form.setMemberId(memberId);
        form.setNames(names);
        form.setLimit("1");
        form.setUnit("3");
        model.addAttribute("form", form);
        return "admin/member_penalize/create";
    }
    
    @PostMapping(path = "/create")
    public String createAction(
            HttpServletRequest request,
            MemberSessionBean mbean,
            @Valid @ModelAttribute("form") MemberPenalizeForm form,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            return "admin/member_penalize/create";
        }
        Member m = memberService.get(form.getMemberId()).orElseThrow(()->new ResourceNotFoundException("会员不存在或暂时无法访问"));
        //
        MemberPenalizeRecords mpr = new MemberPenalizeRecords(
                form.getMemberId(),
                form.getNames(),
                m.getStatus(),
                form.getEnumArrive(),
                form.getEnumUnit(),
                form.getIntegerLimit(),
                form.getReason(),
                form.getEvidences(),
                mbean.getMid(),
                mbean.getNickname());
        String errMsg = "新增惩罚记录操作失败";
        try {
            if (memberPenalizeRecordsService.create(mpr) > 0) {
                return "redirect:/member/penalize/";
            }
        } catch (Exception e) {
            errMsg = e.getMessage();
        }
        model.addAttribute("errors", errMsg);
        model.addAttribute("form", form);
        return "admin/member_penalize/create";
    }
    
    //手动结束惩罚
    @PostMapping(path = "/expire", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removePenalizeAction(
            @RequestParam("id") long id,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->memberPenalizeRecordsService.expired(id)).success("惩罚记录成功结束").error("操作失败");
    }
    
    //会员的惩罚状态
    @GetMapping(path = "/status/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllMemberStatus(HttpServletRequest request, Model model) { //4 会正常不是惩罚状态
        return EnumArchitecture.getInstance(MemberStatusEnum.class).entrySet().stream().filter(x -> x.getKey() < 4).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
    
    //惩罚时长单位
    @GetMapping(path = "/unit/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllTimeUnit(HttpServletRequest request, Model model) {
        return EnumArchitecture.getInstance(ForumCalendarUnitEnum.class);
    }
}